import React, { Component, createContext } from 'react'
import { QuestionCircleOutlined } from '@ant-design/icons';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import {
  Table,
  Input,
  Select,
  Button,
  Modal,
  Tooltip,
  Radio,
  notification,
  Badge,
  Tag,
  Popover,
} from 'antd';
import styles from '@/pages/algorithmModel/dataCenter/style.less';
import { addModel, getModelAlgorithms, getModelList } from '@/services/modelCenter';
import { getDataPurpose, getDataSetList, } from '@/services/dataCenter';

const FormItem = Form.Item;
const { Option } = Select;
const { Search } = Input;
const formItemLayout = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 5 },
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 19 },
  },
};
const bondStyle = {
  fontWeight: 700,
  marginTop: 5
}

class Edit extends Component {
  constructor(props) {
    super(props);
    this.state = {
      dataList: [],
      dataSets: [],
      selectedRowKeys: [],
      loading: false,
      modelType: 0,
      isShowDatasTable: false,
      modelList: [], // 模型列表 从后端获取
      algorithms: [], // 算法列表 从后端获取
      noEntityAlgorithms: [],//算法（是指关系或者属性算法）列表，从后端获取
      algorithmName: '',
      noEntityAlgorithmName: '',//算法（关系或者属性算法）名称
      algorithmId: '',
      noEntityAlgorithmId: '',//算法（关系或者属性算法）ID
      selected: 0,
      krlDataset:{
        TransD:[{value:'FB15K237'}],
        TransE:[{value:'FB15K237'}, {value:'WN18RR'}],
        TransH:[{value:'FB15K237'}],
      },
      extraData:'FB15K237',//存储模型额外的数据 用于记录知识表示学习模型使用的数据集（用英文逗号 , 分隔的数据集名称列表）
    };
  }

  componentDidMount() {
    getDataPurpose({ commonType: 'model_purpose', useType:'model_purpose_model' }).then(rs => {
      if (rs.retCode === '0') {
        this.setState({ modelList: rs.data })
      }
    });
    this.queryAlgorithms();
  }

  // 获取算法
  queryAlgorithms() {
    const { modelType } = this.state;
    if (modelType === 1 || modelType === 4) {
      getModelAlgorithms(modelType).then(res => {
        if (res.retCode === '0') {
          this.setState({ noEntityAlgorithms: res.data, noEntityAlgorithmId: res.data[0].id, noEntityAlgorithmName: res.data[0].algorithmName })
          this.props.form.setFieldsValue({ noEntityAlgorithmId: res.data[0].id })
        }
      })
      getModelAlgorithms(0).then(res => {
        if (res.retCode === '0') {
          this.setState({ algorithms: res.data, algorithmId: res.data[0].id, algorithmName: res.data[0].algorithmName })
          this.props.form.setFieldsValue({ algorithmId: res.data[0].id })
        }
      })
    } else if (modelType === 5) {
      //trigger  查询触发词抽取算法
      getModelAlgorithms(modelType, 'trigger').then(res => {
        if (res.retCode === '0') {
          this.setState({ noEntityAlgorithms: res.data, noEntityAlgorithmId: res.data[0] && res.data[0].id, noEntityAlgorithmName: res.data[0] && res.data[0].algorithmName })
          this.props.form.setFieldsValue({ noEntityAlgorithmId: res.data[0] && res.data[0].id })
        }
      })
      //argument  查询元素抽取算法
      getModelAlgorithms(modelType, 'argument').then(res => {
        if (res.retCode === '0') {
          this.setState({ algorithms: res.data, algorithmId: res.data[0] && res.data[0].id, algorithmName: res.data[0] && res.data[0].algorithmName })
          this.props.form.setFieldsValue({ algorithmId: res.data[0] && res.data[0].id })
        }
      })
    } else {
      getModelAlgorithms(modelType).then(res => {
        if (res.retCode === '0') {
          this.setState({ algorithms: res.data, algorithmId: res.data[0] && res.data[0].id, algorithmName: res.data[0] && res.data[0].algorithmName })
          this.props.form.setFieldsValue({ algorithmId: res.data[0] && res.data[0].id })
        }
      })
    }
  }

  // 名称校验
  onNameBlur = e => {
    const modelNameStrict = e.target.value;
    modelNameStrict && getModelList({ data: { modelNameStrict } }).then(res => {
      if (res.retCode === '0') {
        if (res.data.total > 0) {
          this.props.form.setFields({
            modelName: {
              value: modelNameStrict,
              errors: [new Error('名称已存在!')],
            },
          });
          return;
        }
      }
    })
  }

  // 提交修改的内容
  handleUserSubmit = e => {
    e.preventDefault();
    const _this = this;
    this.props.form.validateFields((err, values) => {
      if (!err) {
        const { dataSets, algorithmName, algorithmId, noEntityAlgorithmName, noEntityAlgorithmId, modelType, extraData } = _this.state;
        if (dataSets.length === 0 && modelType !== 6) {
          notification['warning']({
            message: '警告',
            key: '请添加标注数据集',
            description: '请添加标注数据集',
          });
          return;
        }
        //
        if (noEntityAlgorithmId) {
          values['modelAlgorithm'] = noEntityAlgorithmName
          values['algorithmId'] = noEntityAlgorithmId
          values['anotherModelAlgorithm'] = algorithmName
          values['anotherAlgorithmId'] = algorithmId
        } else {
          values['modelAlgorithm'] = algorithmName
          values['algorithmId'] = algorithmId
          values['anotherModelAlgorithm'] = noEntityAlgorithmName
          values['anotherAlgorithmId'] = noEntityAlgorithmId
        }
        if(modelType===6){
          values['extraData'] = extraData
        }
        // values['propertyAlgorithmName'] = modelType ===4 ? noEntityAlgorithmName : ''
        // values['propertyAlgorithmId'] = modelType ===4 ? noEntityAlgorithmId : ''
        const modelDatasetUsedVOS = []
        dataSets.map((item, index) => {
          modelDatasetUsedVOS[index] = {
            "datasetId": item['dataSetId']
          }
        })
        values['modelDatasetUsedVOS'] = modelDatasetUsedVOS;
        // values['modelAlgorithm'] = algorithmName
        _this.setState({ loading: true, })
        delete values.dataSets;
        addModel(values).then(res => {
          if (res.retCode === '0') {
            notification['success']({
              message: '操作成功',
              key: '操作成功',
              description: '模型新增成功',
            });
            _this.infoToParent(false);
          } else {
            _this.setState({ loading: false, })
          }
        });
      }
    });
  };

  infoToParent(key) {
    this.props.callBack(key);
  }

  //切换选择算法
  onAlgorithmChange(data) {
    const { algorithms, noEntityAlgorithms, modelType, extraData,krlDataset } = this.state;
    if (modelType === 1 || modelType === 4 || modelType === 5) {
      const noEntityAlgorithmName = (noEntityAlgorithms.filter(val => val.id === data))[0]['algorithmName'];
      const noEntityAlgorithmId = data;
      this.setState({ noEntityAlgorithmName, noEntityAlgorithmId });
    } else {
      const algorithmName = (algorithms.filter(val => val.id === data))[0]['algorithmName'];
      const algorithmId = data;
      this.setState({ algorithmName, algorithmId });
      if (modelType === 6){
        this.props.form.setFieldsValue({ extraData:krlDataset[algorithmName] && krlDataset[algorithmName][0].value })
        this.setState({ extraData:krlDataset[algorithmName] && krlDataset[algorithmName][0].value });
      }
    }
  }
  // 知识表示算法切换算法
  onKrlDatasetChange(extraData) {
    this.setState({extraData})
  }

  // 模型类型改变
  modelTypeChange = modelType => {
    // eslint-disable-next-line max-len
    this.setState({ modelType, dataSets: [], selectedRowKeys: [], selected: 0 }, () => {
      this.queryAlgorithms()
    });
  }

  MOD(isShowDatasTable, key) {
    const _this = this;
    if (key === 'cancel') {
      _this.setState({ isShowDatasTable, selectedRowKeys: [], dataSets: [] });
    } else {
      _this.setState({ isShowDatasTable }, () => {
        isShowDatasTable && this.queryDataSet('');
      });
    }
  }

  // 获取数据集列表
  queryDataSet(dataSetName) {
    const { modelType } = this.state;
    let purpose = -2;
    if (modelType !== 0) {
      purpose = modelType;
    }
    getDataSetList({ pageNum: 0, pageSize: 100000, data: { dataSetName, dataSetStatus: 1, purpose } }).then(rs => {
      if (rs.retCode - 0 === 0) {
        this.setState({ dataList: rs.data.list })
      }
    })
  }
  onDataSetSearch(val) {
    this.queryDataSet(val);
  }
  // 标注数据集弹框 标签内容
  labelContent(text, record) {
    let content = <div style={{ maxWidth: 400, maxHeight: 200, overflow: 'auto' }}>
      {record.purpose !== 5 &&
      <><div style={bondStyle}> 实体标签:</div>
        <div>
          {
            record.objectLabelVOList && record.objectLabelVOList.filter(val => val.labelType === 0).map((item, index) =>
              <Tag style={{ marginTop: 8 }}>{item.labelName}</Tag>)
          }
        </div>
      </>
      }
      {record.purpose === 1 && <><div style={bondStyle}> 关系：</div>
        <div>
          {
            record.relationLabelVOList && record.relationLabelVOList.map(item => <div style={{ marginTop: 8 }}>{`${item.labelRelationName} : ${item.labelFromName} ->${item.labelToName}`} </div>)
          }
        </div></>}
      {record.purpose === 4 && <><div style={bondStyle}> 属性标签:</div>
        <div>
          {
            record.objectLabelVOList && record.objectLabelVOList.filter(val => val.labelType === 1).map((item, index) => <Tag style={{ marginTop: 8 }}>{item.labelName}</Tag>)
          }
        </div>
        <div style={bondStyle}> 实体属性:</div>
        <div>
          {
            record.relationLabelVOList && record.relationLabelVOList.map(item => <div style={{ marginTop: 8 }}>{`${item.labelRelationName} : ${item.labelFromName} ->${item.labelToName}`} </div>)
          }
        </div></>
      }
      {record.purpose === 5 && <>
        <div style={bondStyle}> 事件类型标签:</div>
        <div>
          {
            record.objectLabelVOList && record.objectLabelVOList.filter(val => val.labelType === 0).map((item, index) => <Tag style={{ marginTop: 8 }}>{item.labelName}</Tag>)
          }
        </div>
        <div style={bondStyle}> 实体类型标签:</div>
        <div>
          {
            record.objectLabelVOList && record.objectLabelVOList.filter(val => val.labelType === 1).map((item, index) => <Tag style={{ marginTop: 8 }}>{item.labelName}</Tag>)
          }
        </div>
        <div style={bondStyle}> 角色映射:</div>
        <div>
          {
            record.relationLabelVOList && record.relationLabelVOList.map(item => <div style={{ marginTop: 8 }}>{`${item.labelRelationName} : ${item.labelFromName} ->${item.labelToName}`} </div>)
          }
        </div>
      </>
      }
    </div>
    return record.purpose === 3 ? 1 :
      <Popover content={content}><span style={{ color: '#29CCB1' }}>{record.purpose === 3 ? 1 : (record.objectLabelVOList === null ? 0 : record.objectLabelVOList.length)}</span></Popover>;
  }

  render() {
    const { loading, modelType, isShowDatasTable, selected, dataList, algorithms, algorithmId, selectedRowKeys, modelList, dataSets, noEntityAlgorithms, noEntityAlgorithmId
      ,krlDataset, algorithmName,extraData } = this.state;
    const { form, isShowAddDataModel } = this.props;
    const { getFieldDecorator } = form;
    let newModelList = modelList.slice(0);
    // newModelList.pop();

    const columns = [
      { title: '数据集名称', dataIndex: 'dataSetName', key: 'dataSetName' },
      {
        title: '数据用途', dataIndex: 'purpose', key: 'purpose', render: record => {
          // eslint-disable-next-line max-len
          return modelList.filter(model => record - 0 === model.commonValue - 0)[0].commonName
        },
      },
      {
        title: '标签', dataIndex: 'objectLabelVOList', key: 'objectLabelVOList',
        render: (text, record) => this.labelContent(text, record),
      },
      { title: '创建时间', dataIndex: 'createTimeShort', key: 'createTimeShort' },
    ];
    const rowSelection = {
      onChange: (selectedRowKeys, selectedRows) => {
        let selected = 0, dataSets = [];
        selectedRows.map(val => {
          selected += Number(val.segmentNum);
          val['datasetId'] = val.dataSetId;
          dataSets.push(val)
        })
        this.setState({ selected, selectedRowKeys, dataSets });
      },
      selectedRowKeys,
      // getCheckboxProps: record => ({
      //     defaultChecked: selectedRowKeys.includes(`${record.dataSetId}`),
      // }),
    };

    return <>
        <Modal
          title={'新增模型'}
          maskClosable={false}
          width={600}
          visible={isShowAddDataModel}
          onCancel={this.infoToParent.bind(this, false)}
          footer={[
            <Button key="cancel" onClick={this.infoToParent.bind(this, false)}>取消</Button>,
            <Button key="primary" type='primary' loading={loading} onClick={this.handleUserSubmit}>确定</Button>
          ]}
        >

          <Form>
            <Form.Item label="模型名称" {...formItemLayout}>
              {getFieldDecorator('modelName', {
                rules: [{ required: true, pattern: /^[\u4e00-\u9fa5\w]{1,20}$/, message: '模型名称不为空、不允许特殊字符且长度不超过20!' }],
              })(
                <Input placeholder="模型名称" style={{ width: 400 }} onBlur={this.onNameBlur.bind(this)} />,
              )}
            </Form.Item>

            <Form.Item label="模型类型" {...formItemLayout}>
              {getFieldDecorator('modelType', {
                rules: [{ required: true }],
                initialValue: modelType,
              })(
                <Select placeholder="请选择模型类型" showSearch onChange={this.modelTypeChange} style={{ width: 400 }}>
                  {
                    newModelList.map(val =>
                      // eslint-disable-next-line max-len
                      <Select.Option key={val.commonName} value={val.commonValue - 0}>{val.commonName}</Select.Option>)
                  }
                </Select>,
              )}
            </Form.Item>
            {modelType !== 5 ?
              <Form.Item label={modelType !== 6 ? '实体识别算法' : '知识表示算法'} {...formItemLayout}>
                {getFieldDecorator('algorithmId', {
                  rules: [{ required: true, message: '请选择模型算法!' }],
                  initialValue: algorithmId,
                })(
                  <Select placeholder="模型算法" showSearch style={{ width: 400 }} onChange={this.onAlgorithmChange.bind(this)} filterOption={(input, option) =>
                    ('' + option.props.children).toLowerCase().indexOf(input.toLowerCase()) >= 0
                  }>
                    {
                      algorithms.map(val =>
                        <Select.Option key={val.algorithmName} value={val.id}>{val.algorithmName}</Select.Option>)
                    }
                  </Select>
                )}
              </Form.Item> : null
            }
            {modelType === 5 ? <>
                <Form.Item label="实体识别算法" {...formItemLayout}>
                  {getFieldDecorator('elementAlgorithmId', {
                    rules: [{ required: true, message: '请选择元素抽取算法!' }],
                    initialValue: algorithmId,
                  })(
                    <Select placeholder="模型算法" showSearch style={{ width: 400 }} onChange={this.onAlgorithmChange.bind(this)} filterOption={(input, option) =>
                      ('' + option.props.children).toLowerCase().indexOf(input.toLowerCase()) >= 0
                    }>
                      {
                        algorithms.map(val =>
                          <Select.Option key={val.algorithmName} value={val.id}>{val.algorithmName}</Select.Option>)
                      }
                    </Select>
                  )}
                </Form.Item>
                <Form.Item label="事件抽取算法" {...formItemLayout}>
                  {getFieldDecorator('triggerAlgorithmId', {
                    rules: [{ required: true, message: '请选择触发词抽取算法!' }],
                    initialValue: noEntityAlgorithmId,
                  })(
                    <Select placeholder="模型算法" showSearch style={{ width: 400 }} onChange={this.onAlgorithmChange.bind(this)} filterOption={(input, option) =>
                      ('' + option.props.children).toLowerCase().indexOf(input.toLowerCase()) >= 0
                    }>
                      {
                        noEntityAlgorithms.map(val =>
                          <Select.Option key={val.algorithmName} value={val.id}>{val.algorithmName}</Select.Option>)
                      }
                    </Select>
                  )}
                </Form.Item>
              </>
              : null
            }
            {(modelType === 1 || modelType === 4) ?
              <Form.Item label={modelType === 1 ? '关系抽取算法' : '属性抽取算法'} {...formItemLayout}>
                {getFieldDecorator('noEntityAlgorithmId', {
                  rules: [{ required: true, message: modelType === 1 ? '关系抽取算法' : '属性抽取算法' }],
                  initialValue: noEntityAlgorithmId,
                })(
                  <Select placeholder={modelType === 1 ? '关系抽取算法' : '属性抽取算法'} showSearch style={{ width: 400 }} onChange={this.onAlgorithmChange.bind(this)} filterOption={(input, option) =>
                    ('' + option.props.children).toLowerCase().indexOf(input.toLowerCase()) >= 0
                  }>
                    {
                      // eslint-disable-next-line max-len
                      noEntityAlgorithms.map(val => <Option key={val.algorithmName} value={val.id}>{val.algorithmName}</Option>)
                    }
                  </Select>
                )}
              </Form.Item> : null
            }

            {modelType !== 6 && <Form.Item
              label={
                <span>
                <span className={styles.lableRequire}>*</span>
                  {'训练数据集'}
                  {/*<Tooltip title={'训练模型使用的数据集选择。内容为“数据中心”中状态为已标注，且已生成可训练json的数据集'}>*/}
                  <Tooltip title={'选择的是数据中心标注的数据作为训练文档，不少于4篇文档用于训练。'}>
                  <QuestionCircleOutlined style={{color: '#8795A1', margin: '0 2px'}} />
                </Tooltip>
              </span>
              } {...formItemLayout}>
              {
                getFieldDecorator('dataSets', {
                  rules: [{message: '请添加训练数据集!'}],
                })(
                  <>
                    <Button type="dashed" block style={{width: 400, marginRight: '10px'}}
                            onClick={this.MOD.bind(this, true)}>+添加标注数据集</Button>
                    {
                      // eslint-disable-next-line max-len
                      dataSets.map(val => <Tag key={val.dataSetId} id={val.dataSetId}>{val.dataSetName}</Tag>)
                    }
                  </>,
                )
              }
            </Form.Item>}
            {modelType === 6 ?
              <Form.Item label='数据集' {...formItemLayout}>
                {getFieldDecorator('extraData', {
                  rules: [{ required: true, message: '数据集' }],
                  initialValue: extraData,
                })(
                  <Select showSearch style={{ width: 400 }} onChange={this.onKrlDatasetChange.bind(this)}
                  //         filterOption={(input, option) =>
                  //   ('' + option.props.children).toLowerCase().indexOf(input.toLowerCase()) >= 0
                  // }
                  >
                    <Option key='FB15K237' value='FB15K237'>FB15K237</Option>
                    {
                      // eslint-disable-next-line max-len
                      algorithmName === 'TransE' &&  <Option key='WN18RR' value='WN18RR'>WN18RR</Option>
                    }
                  </Select>
                )}
              </Form.Item> : null
            }
          </Form>
        </Modal>

        {isShowDatasTable &&
        <Modal
          title={'选择标注数据集'}
          maskClosable={false}
          width={800}
          visible={isShowDatasTable}
          onCancel={this.MOD.bind(this, false, 'cancel')}
          footer={[
            <span key="span" style={{ color: 'rgba(135, 149, 161, 1)', padding: '0 16px' }}>至少选择 4 篇文档训练，已选择 {selected}</span>,
            <Button key="cancel" onClick={this.MOD.bind(this, false, 'cancel')}>取消</Button>,
            <Button disabled={selected > 3 ? false : true} key="primary" type='primary' loading={loading} onClick={this.MOD.bind(this, false, 'confirm')}>确定</Button>
          ]}
        >
          <Search placeholder="数据集名称" onSearch={value => this.onDataSetSearch(value)} style={{ width: 200, marginBottom: 16 }} />
          <Table rowSelection={rowSelection} columns={columns} dataSource={dataList} size='small' rowKey={record => record.dataSetId} />
        </Modal>
        }

      </>;
  }
}
const Add = Form.create()(Edit);

export default Add
